// ignore_for_file: unnecessary_null_comparison

import 'dart:async';
import 'package:video_setting/pages/video_setting/lock/unicom_synchronized.dart';

class UnicomBasicLock implements Lock {
  Future<dynamic>? last;

  @override
  bool get locked => last != null;

  @override
  Future<T> synchronized<T>(FutureOr<T> Function() func, {Duration? timeout}) async {
    final prev = last;
    final completer = Completer.sync();
    last = completer.future;
    try {
      if (prev != null) {
        if (timeout != null) {
          await prev.timeout(timeout);
        } else {
          await prev;
        }
      }

      var result = func();
      if (result is Future) {
        return await result;
      } else {
        return result;
      }
    } finally {
      void _complete() {
        if (identical(last, completer.future)) {
          last = null;
        }
        completer.complete();
      }

      if (prev != null && timeout != null) {
        prev.then((_) {
          _complete();
        });
      } else {
        _complete();
      }
    }
  }

  @override
  String toString() {
    return 'Lock[${identityHashCode(this)}]';
  }

  @override
  bool get inLock => locked;
}
